package com.hd.pzhwlxt.controller;


import cn.hutool.core.io.FileUtil;
import com.hd.pzhwlxt.utils.FileUploadUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("file")
public class FileController {

    //上传图片
    @PostMapping("upload")
    public String upload(@RequestParam MultipartFile file){
        String url = FileUploadUtil.saveFileAndReturnUrl(file);
        return url;
    }

    //调用图片
    @GetMapping("photo/{photoname}")
    public void download(@PathVariable String photoname, HttpServletResponse response) throws IOException {
        File file = FileUploadUtil.getFile(photoname);
        System.out.println(photoname);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(photoname, "UTF-8"));
        response.setContentType("application/octet-stream");
        // 读取文件的字节流
        os.write(FileUtil.readBytes(file));
        os.flush();
        os.close();
    }
}
